<template>
	<view class="container" v-if="!loading">
		<!-- main begin -->
		<view class="main" v-if="goods.length">
			<headerInfo>
				<!-- 倒计时 -->
				<view class="box" v-if="isAttendance">
					<view class="left_box" v-if="totalSeconds!=0">
						<view class="left_item"></view>
					</view>
					<view class="mask">{{totalSeconds}}</view>
				</view>
			</headerInfo>
			<!-- 主体内容 begin -->
			<view class="content">
				<!-- 左侧菜单 -->
				<scroll-view class="menus" :scroll-into-view="menuScrollIntoView" scroll-with-animation scroll-y>
					<view class="wrapper">
						<view class="menu" :id="`menu-${gItem.id}`" :class="{'current': gItem.id === currentCateId}"
							v-for="(gItem, gIndex) in goods" :key="gIndex" @tap="handleMenuTap(gItem.id)">
							<text>{{ gItem.name }}</text>
							<view class="dot" v-show="menuCartNum(gItem.id)">{{ menuCartNum(gItem.id) }}</view>
						</view>
					</view>
				</scroll-view>
				<scroll-view class="goods" scroll-with-animation scroll-y :scroll-top="cateScrollTop"
					@scroll="handleGoodsScroll">
					<view class="wrapper">
						<!-- 商品轮播 begin -->
						<!-- <swiper class="ads" id="ads" autoplay :interval="3000" indicator-dots>
							<swiper-item v-for="(item, index) in ads" :key='index'>
								<image :src="item.image"></image>
							</swiper-item>
						</swiper> -->
						<!-- 商品轮播 end -->
						<view class="list">
							<!-- category begin -->
							<view class="category" v-for="(gItem, index) in goods" :key="index"
								:id="`cate-${gItem.id}`">
								<view class="title">
									<text>{{ gItem.name }}</text>
									<!-- <image :src="gItem.icon" class="icon"></image> -->
								</view>
								<view class="items">
									<!-- 商品 begin -->
									<view class="good" v-for="(showGood, gKey) in gItem.goods_list" :key="gKey">
										<!-- <image :src="showGood.images" class="image" -->

										<image v-if="gItem.name=='无痕内衣'"
											src="https://wx4.sinaimg.cn/mw690/64be6620ly1hsgup6bwnwj20m80m8t9w.jpg"
											class="image" @tap="showGoodDetailModal(gItem, showGood)">
										</image>
										<image v-if="gItem.name=='内裤'"
											src="http://t14.baidu.com/it/u=3732131680,3428098021&fm=224&app=112&f=JPEG?w=500&h=500"
											class="image" @tap="showGoodDetailModal(gItem, showGood)">
										</image>
										<image v-if="gItem.name=='袜子'"
											src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fimgextra%2Fi4%2F3171618267%2FTB2HmCwnyFTMKJjSZFAXXckJpXa_%21%213171618267.jpg&refer=http%3A%2F%2Fimg.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1726237557&t=54daad38e97c4c1f116f6d167c6ddfb1"
											class="image" @tap="showGoodDetailModal(gItem, showGood)">
										</image>
										<view class="right">
											<text class="name">{{ showGood.name }}</text>
											<text class="tips">{{ showGood.content }}</text>
											<view class="price_and_action">
												<text class="price">￥{{ showGood.price }}</text>
												<view class="btn-group">
													<button type="primary" class="btn property_btn" hover-class="none"
														size="mini" @tap="showGoodDetailModal(gItem, showGood)">
														选规格
													</button>
													<view class="dot" v-show="goodCartNum(showGood.id)">
														{{ goodCartNum(showGood.id) }}
													</view>
												</view>
											</view>
										</view>
									</view>
									<!-- 商品 end -->
								</view>
							</view>
							<!-- category end -->
						</view>
					</view>
				</scroll-view>
			</view>
			<!-- 主体内容 end -->
			<!-- 购物车栏 begin -->
			<view class="cart-box" v-if="shopCart.length > 0">
				<view class="mark">
					<image src="/static/images/menu/cart.png" class="cart-img" @tap="openCartPopup"></image>
					<view class="tag">{{ getCartGoodsNumber }}</view>
				</view>
				<view class="price">￥{{ getCartGoodsPrice }}</view>
				<button type="primary" class="pay-btn" @tap="toPay" :disabled="disabledPay">
					{{ disabledPay ? `差${spread}元起送` : '去结算' }}
				</button>
			</view>
			<!-- 购物车栏 end -->
		</view>
		<!-- main end -->

		<!-- 商品详情模态框 begin -->
		<modal :show="goodDetailModalVisible" class="good-detail-modal" color="#5A5B5C" width="92%" custom
			padding="0rpx" radius="12rpx">
			<view class="cover">
				<!-- <image v-if="goodDetail.images" :src="goodDetail.images" class="image" @tap="handleTopImageClick"> -->
				<image v-if="goodDetail.images && goodDetail.itemName=='无痕内衣'" src="http://caizi-image.oss-cn-shenzhen.aliyuncs.com/guangao1.png"
					class="image" @tap="handleTopImageClick">
				</image>
				<image v-if="goodDetail.images && goodDetail.itemName=='内裤'" src="http://t14.baidu.com/it/u=3732131680,3428098021&fm=224&app=112&f=JPEG?w=500&h=500"
					class="image" @tap="handleTopImageClick">
				</image>
				<image v-if="goodDetail.images && goodDetail.itemName=='袜子'" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fimgextra%2Fi4%2F3171618267%2FTB2HmCwnyFTMKJjSZFAXXckJpXa_%21%213171618267.jpg&refer=http%3A%2F%2Fimg.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1726237557&t=54daad38e97c4c1f116f6d167c6ddfb1"
					class="image" @tap="handleTopImageClick">
				</image>
				
				<!-- <image v-if="goodDetail.images" src="/static/816.png" class="image" @tap="handleTopImageClick"></image> -->
				<view class="btn-group">
					<!-- <image src="/static/images/menu/share-good.png"></image> -->
					<image src="/static/images/menu/close.png" @tap="closeGoodDetailModal"></image>
				</view>
			</view>
			<scroll-view class="detail" scroll-y>
				<view class="wrapper">
					<!-- 基础信息 -->
					<view class="basic">
						<view class="name">{{ goodDetail.name }}</view>
						<view class="tips">{{ goodDetail.content }}</view>
					</view>
					<!-- sku -->
					<view class="properties">
						<view class="property" v-for="(pItem, index) in goodDetail.property" :key="index">
							<view class="title">
								<text class="name">{{ pItem.name }}</text>
								<view class="desc" v-if="pItem.desc">({{ pItem.desc }})</view>
							</view>
							<view class="values">
								<view class="value" v-for="(value, key) in pItem.values" :key="key"
									:class="{'default': value.is_default}" @tap="changePropertyDefault(index, key)">
									{{ value.value }}
								</view>
							</view>
						</view>
					</view>
					<!-- 详情图片 -->
					<view class="pic-group">
						<!-- <image src="/static/01.jpg" mode="scaleToFill"></image> -->
						<!-- <image src="/static/02.jpg" mode="widthFix" @tap="handleDetailImageClick"></image>
						<image src="/static/03.jpg" mode="widthFix"></image> -->
					</view>
				</view>
			</scroll-view>
			<view class="action">
				<view class="left">
					<view class="price">￥{{ goodDetail.price }}</view>
					<view class="props" v-if="getGoodSelectedProps(goodDetail)">
						{{ getGoodSelectedProps(goodDetail) }}
					</view>
				</view>
				<view class="btn-group">
					<button type="default" plain class="btn" size="mini" hover-class="none" @tap="handlePropertyReduce">
						<view class="iconfont iconsami-select"></view>
					</button>
					<view class="number">{{ goodDetail.number }}</view>
					<button type="primary" class="btn" size="min" hover-class="none" @tap="handlePropertyAdd">
						<view class="iconfont iconadd-select"></view>
					</button>
				</view>
			</view>
			<view class="add-to-cart-btn" @tap="handleAddToCartInModal">
				<view>加入购物车</view>
			</view>
		</modal>
		<!-- 商品详情模态框 end -->



		<!-- 购物车详情popup begin-->
		<popup-layer direction="top" :show-pop="cartPopupVisible" class="cart-popup" @closeCallBack='openCartPopup'>
			<template slot="content">
				<view class="top">
					<text @tap="handleCartClear">清空</text>
				</view>
				<scroll-view class="cart-list" scroll-y>
					<view class="wrapper">
						<view class="item" v-for="(item, index) in shopCart" :key="index">
							<view class="left">
								<view class="name">{{ item.name }}</view>
								<view class="props">{{ item.props_text }}</view>
							</view>
							<view class="center">
								<text>￥{{ item.price }}</text>
							</view>
							<view class="right">
								<button type="default" plain size="mini" class="btn" hover-class="none"
									@tap="handleCartItemReduce(e,index)">
									<view class="iconfont iconsami-select"></view>
								</button>
								<view class="number">{{ item.number }}</view>
								<button type="primary" class="btn" size="min" hover-class="none"
									@tap="handleCartItemAdd(e,index)">
									<view class="iconfont iconadd-select"></view>
								</button>
							</view>
						</view>
						<view class="item" v-if="orderType == 'takeout' && store.packing_fee">
							<view class="left">
								<view class="name">包装费</view>
							</view>
							<view class="center">
								<text>￥{{ parseFloat(store.packing_fee) }}</text>
							</view>
							<view class="right invisible">
								<button type="default" plain size="mini" class="btn" hover-class="none">
									<view class="iconfont iconsami-select"></view>
								</button>
								<view class="number">1</view>
								<button type="primary" class="btn" size="min" hover-class="none">
									<view class="iconfont iconadd-select"></view>
								</button>
							</view>
						</view>
					</view>
				</scroll-view>
			</template>
		</popup-layer>
		<!-- 购物车详情popup end-->

		<!-- 签到成功 begin -->
		<modal custom :show="attendanceModalVisible">
			<view class="attendance-modal">
				<view class="modal-header">
					<image src="/static/images/attendance/cup.png" mode="widthFix"></image>
				</view>
				<view
					class="modal-content d-flex align-items-center just-content-center flex-column font-size-sm text-color-base">
					<view>赠送的1积分已发到您的账户中</view>
					<view>连续签到1天可额外获得1积分</view>
				</view>
				<view class="d-flex align-items-center just-content-center">
					<button type="primary" class="btn" @tap="attendanceModalVisible=false">我知道了</button>
				</view>
			</view>
		</modal>
		<!-- 签到成功 end -->
	</view>
	<view class="loading" v-else>
		<!-- <image src="/static/images/loading.gif"></image> -->
	</view>


</template>

<script>
	import headerInfo from './header-info.vue'
	import modal from '@/components/modal/modal'
	import popupLayer from '@/components/popup-layer/popup-layer'
	import {
		mapState,
		mapMutations,
		mapActions,
		mapGetters
	} from 'vuex'

	export default {
		components: {
			headerInfo,
			modal,
			popupLayer,
		},
		data() {
			return {
				goods: [], //所有商品
				ads: [{
						image: 'https://img-shop.qmimg.cn/s23107/2020/04/27/4ebdb582a5185358c4.jpg?imageView2/2/w/600/h/600'
					},
					{
						image: 'https://images.qmai.cn/s23107/2020/05/08/c25de6ef72d2890630.png?imageView2/2/w/600/h/600'
					},
					{
						image: 'https://img-shop.qmimg.cn/s23107/2020/04/10/add546c1b1561f880d.jpg?imageView2/2/w/600/h/600'
					},
					{
						image: 'https://images.qmai.cn/s23107/2020/04/30/b3af19e0de8ed42f61.jpg?imageView2/2/w/600/h/600'
					},
					{
						image: 'https://img-shop.qmimg.cn/s23107/2020/04/17/8aeb78516d63864420.jpg?imageView2/2/w/600/h/600'
					}
				],
				loading: true,
				currentCateId: 6208, //默认分类
				cateScrollTop: 0,
				sizeCalcState: false,
				menuScrollIntoView: '',
				goodDetailModalVisible: false, // 是否商品详情模态框
				goodDetail: {}, // 当前商品信息
				category: {}, // 当前商品所在分类
				// 签到相关参数
				isAttendance: false,
				attendanceModalVisible: false,
				totalSeconds: 10,
				atdTimer: null,
			}
		},
		async onLoad() {
			await this.init()
		},
		onShow() {
			if (uni.getStorageSync('isAttendance')) {
				this.isAttendance = true
				this.startCountdown();
			}
		},
		onHide() {
			this.clearTimer();
			this.isAttendance = false
			uni.setStorageSync('isAttendance', false);
		},
		computed: {
			...mapState(['cartPopupVisible', 'shopCart', 'orderType', 'store']),
			...mapGetters(['isLogin', 'goodCartNum', 'menuCartNum', 'getCartGoodsNumber', 'getCartGoodsPrice']),
			disabledPay() { //是否达到起送价
				return this.orderType == 'takeout' && (this.getCartGoodsPrice < this.store.min_price) ? true : false
			},
			spread() { //差多少元起送
				if (this.orderType != 'takeout') return
				return parseFloat((this.store.min_price - this.getCartGoodsPrice).toFixed(2))
			}
		},
		methods: {
			...mapMutations([
				"SET_CART_POPUP_VISIBLE",
				'SET_SHOP_CART',
				"ADD_SHOP_CART",
				"REDUCE_SHOP_CART",
				"REMOVE_SHOP_CART",
			]),
			...mapActions(['getStore']),
			async init() { //页面初始化
				this.loading = true
				await this.getStore()
				this.goods = await this.$api('goods')
				console.log('商品列表', JSON.parse(JSON.stringify(this.goods)))
				this.loading = false
				// this.$store.commit('SET_SHOP_CART', uni.getStorageSync('cart') || [])
				this.SET_SHOP_CART(uni.getStorageSync('cart') || [])
				this.$nextTick(() => this.handleMenuTap(6208))

			},
			// 倒计时开始
			startCountdown() {
				this.atdTimer = setInterval(() => {
					if (this.totalSeconds > 0) {
						this.totalSeconds -= 1;
					} else {
						this.clearTimer();
						this.isAttendance = false
						uni.setStorageSync('isAttendance', false);
						this.attendanceModalVisible = true
						console.log('签到成功')
					}
				}, 1000);
			},
			// 清除定时器
			clearTimer() {
				console.log('清楚定时器', this.atdTimer)
				if (this.atdTimer) {
					clearInterval(this.atdTimer);
					this.atdTimer = null;
					this.totalSeconds = 10
				}
			},
			// 放大商品图
			handleTopImageClick(event) {
				console.log('放大商品图', event)
				uni.previewImage({
					current: 'https://wx4.sinaimg.cn/mw690/64be6620ly1hsgup6bwnwj20m80m8t9w.jpg', // 当前显示图片的链接（必填）
					urls: [
						'https://wx4.sinaimg.cn/mw690/64be6620ly1hsgup6bwnwj20m80m8t9w.jpg'
					] // 所有图片的链接列表（必填）
				});
			},
			// 放大详情图
			handleDetailImageClick(event) {
				console.log('放大详情图', event)
				uni.previewImage({
					current: 'https://p26-item.ecombdimg.com/img/ecom-shop-material/xRMFgJHT_m_7b904a9a00415a292da23e5fc57bc932_sx_284366_www790-1500~tplv-5mmsx3fupr-resize:790:1500.jpeg', // 当前显示图片的链接（必填）
					urls: [
						'https://p26-item.ecombdimg.com/img/ecom-shop-material/xRMFgJHT_m_7b904a9a00415a292da23e5fc57bc932_sx_284366_www790-1500~tplv-5mmsx3fupr-resize:790:1500.jpeg'
					] // 所有图片的链接列表（必填）
				});
			},
			// 去结算
			toPay() {
				uni.showLoading({
					title: '加载中'
				})
				uni.setStorageSync('cart', JSON.parse(JSON.stringify(this.shopCart)))

				uni.navigateTo({
					url: '/packagesB/pay/pay'
				})
				uni.hideLoading()
			},

			//点击菜单项事件
			handleMenuTap(id) {
				if (!this.sizeCalcState) {
					this.calcSize()
				}
				this.currentCateId = id
				console.log('点击侧边菜单', this.currentCateId, this.goods)
				this.$nextTick(() => this.cateScrollTop = this.goods.find(item => item.id == id).top)
			},
			//商品列表滚动事件
			handleGoodsScroll({
				detail
			}) {
				if (!this.sizeCalcState) {
					this.calcSize()
				}
				const {
					scrollTop
				} = detail
				let tabs = this.goods.filter(item => item.top <= scrollTop).reverse()
				if (tabs.length > 0) {
					this.currentCateId = tabs[0].id
				}
			},
			calcSize() {
				console.log('开始裁剪高度')
				let h = 0

				// let view = uni.createSelectorQuery().select('#ads')
				// view.fields({
				// 	size: true
				// }, data => {
				// 	h += Math.floor(data.height)
				// }).exec()
				console.log('1正在裁剪', this.goods)
				this.goods.forEach(item => {
					let view = uni.createSelectorQuery().select(`#cate-${item.id}`)
					console.log('2获取dom', view)
					view.fields({
						size: true
					}, data => {
						console.log('3准备增加高度', data)
						item.top = h
						h += data.height
						item.bottom = h
					}).exec()
				})
				this.sizeCalcState = true
			},
			//添加到购物车
			handleAddToCart(cate, cGood, num) {
				const fIndex = this.shopCart.findIndex(fItem => {
					return (fItem.id === cGood.id) && (fItem.props_text === cGood.props_text)
				})
				let newArr = JSON.parse(JSON.stringify(this.shopCart))
				if (fIndex > -1) {
					newArr[fIndex].number += num
				} else {
					newArr.push({
						id: cGood.id,
						cate_id: cate.id,
						name: cGood.name,
						price: cGood.price,
						number: num,
						image: cGood.images,
						use_property: cGood.use_property,
						props_text: cGood.props_text,
						props: cGood.props
					})
				}
				// this.$store.commit('SET_SHOP_CART', newArr)
				this.SET_SHOP_CART(newArr)
			},
			// 开启详情模态框
			showGoodDetailModal(item, goodDetail) {
				console.log('详情', item,goodDetail)
				this.goodDetail = JSON.parse(JSON.stringify({
					...goodDetail,
					number: 1,
					itemName:item.name
				}))
				this.category = JSON.parse(JSON.stringify(item))
				this.goodDetailModalVisible = true
			},
			//关闭详情模态框
			closeGoodDetailModal() {
				this.goodDetailModalVisible = false
				this.category = {}
				this.goodDetail = {}
			},
			//设置默认sku
			changePropertyDefault(index, key) {
				this.goodDetail.property[index].values.forEach(value => this.$set(value, 'is_default', 0))
				this.goodDetail.property[index].values[key].is_default = 1
				this.goodDetail.number = 1
			},
			//计算当前商品所选sku
			getGoodSelectedProps(selectGood, type = 'text') {
				console.log(('当前选择商品'), selectGood)
				if (JSON.stringify(selectGood) !== '{}') {
					let props = []
					selectGood.property.forEach(({
						values
					}) => {
						values.forEach(value => {
							if (value.is_default) {
								props.push(type === 'text' ? value.value : value.id)
							}
						})
					})
					return type === 'text' ? props.join('，') : props
				}
				return ''
			},
			// 增加
			handlePropertyAdd() {
				this.goodDetail.number += 1
			},
			// 减少
			handlePropertyReduce() {
				if (this.goodDetail.number === 1) return
				this.goodDetail.number -= 1
			},
			// 处理选中的商品的参数
			handleAddToCartInModal() {
				const product = Object.assign({}, this.goodDetail, {
					props_text: this.getGoodSelectedProps(this.goodDetail),
					props: this.getGoodSelectedProps(this.goodDetail, 'id')
				})
				console.log('加入购物车', product)
				this.handleAddToCart(this.category, product, this.goodDetail.number)
				this.closeGoodDetailModal()
			},
			// 开/关购物车
			openCartPopup() {
				// this.$store.commit("SET_CART_POPUP_VISIBLE", !this.cartPopupVisible);
				this.SET_CART_POPUP_VISIBLE(!this.cartPopupVisible)
			},
			// 购物车增加
			handleCartItemAdd: function(e, iIndex) {
				// this.$store.commit("ADD_SHOP_CART", iIndex);
				this.ADD_SHOP_CART(iIndex);
			},
			// 购物车减少
			handleCartItemReduce: function(e, rIndex) {
				// this.$store.commit("REDUCE_SHOP_CART", rIndex);
				this.REDUCE_SHOP_CART(rIndex)
			},
			//清空购物车
			handleCartClear() {
				uni.showModal({
					title: "提示",
					content: "确定清空购物车么",
					success: ({
						confirm
					}) => {
						if (confirm) {
							// this.$store.commit("SET_CART_POPUP_VISIBLE", false);
							// this.$store.commit("REMOVE_SHOP_CART", []);
							this.SET_CART_POPUP_VISIBLE(false)
							this.REMOVE_SHOP_CART([])
						}
					},
				});
			},
		}
	};
</script>

<style lang="scss" scoped>
	@import '~@/pages/menu/menu.scss';

	.attendance-modal {
		.modal-header {
			width: 100%;
			margin-top: -180rpx;
			position: relative;

			image {
				width: 100%;
			}
		}

		.modal-content {
			height: 200rpx;
		}

		.btn {
			width: 100%;
			border-radius: 50rem;
			font-size: $font-size-lg;
		}
	}
</style>